<template>
  <div class="compact-container">
    <!-- Compact search row with Add button on the right -->
    <div class="search-row">
      <span class="search-label">供应商昵称：</span>
      <el-input v-model="Vendor_name" size="small" class="search-input" />
      <span class="search-label">采购入库编号：</span>
      <el-input v-model="Pb_code" size="small" class="search-input" />
      <el-button type="primary" size="small" @click="query">查询</el-button>
      <el-button size="small" @click="reset">重置</el-button>
      <div class="flex-grow"></div>
      <el-button type="primary" size="small" @click="addEdit">添加</el-button>
    </div>

    <el-divider style="margin: 6px 0" />

    <!-- Compact table area -->
    <div class="table-wrapper">
      <el-table 
        :data="flattenedData" 
        border 
        style="width: 100%"
        :cell-style="{ textAlign: 'center', padding: '4px 0' }"
        :header-cell-style="{
          textAlign: 'center',
          background: '#f5f7fa',
          fontWeight: 'bold',
          position: 'sticky',
          top: 0,
          padding: '4px 0',
          height: '36px'
        }"
        :row-style="{ height: '36px' }"
        :span-method="objectSpanMethod"
        v-loading="loading"
      >
        <!-- Table columns -->
        <el-table-column fixed width="180px" prop="pb_code" label="订单编号">
          <template #default="scope">
            <el-link type="primary" @click="infoPage(scope.row)">{{ scope.row.pb_code }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="pb_state" label="订单状态" width="90px">
          <template #default="{row}">{{ getStateText(row.po_state) }}</template>
        </el-table-column>
        <el-table-column prop="pb_Audit" label="是否审核" width="100px">
          <template #default="{row}">{{ getAuditText(row.pb_Audit) }}</template>
        </el-table-column>
        <el-table-column prop="po_name" label="采购订单昵称" width="180px" />
        <el-table-column prop="vendor_name" label="供应商" width="180px" />
        <el-table-column prop="pro_name" width="150px" label="产品昵称" />
        <el-table-column prop="pro_code" width="180px" label="产品编号" />
        <el-table-column prop="pro_brand" width="120px" label="品牌" />
        <el-table-column prop="pro_model" width="150px" label="规格型号" />
        <el-table-column prop="details_monovalent" width="120px" label="单价" align="right" />
        <el-table-column label="小计" width="120px" align="right">
          <template #default="{row}">{{ calculateSubtotal(row) }}</template>
        </el-table-column>
        <el-table-column prop="po_number" width="100px" label="采购数量" align="right" />
        <el-table-column prop="to_be_stored_qty" label="待入库数量" width="80px" />
        <el-table-column prop="details_storage" label="已入库数量" width="120px" />
        <el-table-column label="未入库数量" width="130px">
          <template #default="{row}">{{ dairuku(row) }}</template>
        </el-table-column>
        <el-table-column prop="po_rep_id" label="采购负责人" width="120px">
          <template #default="scope">{{ userValue(scope.row.po_rep_id) }}</template>
        </el-table-column>
        <el-table-column prop="warehouse_code" label="入库仓库" width="150px">
          <template #default="scope">{{ cwVaule(scope.row.warehouse_code) }}</template>
        </el-table-column>
        <el-table-column prop="operation" fixed="right" label="操作" width="180px">
          <template #default="scope">
            <div class="action-group">
              <el-button 
                size="small" 
                @click="handleEdit(scope.row)"
                :disabled="scope.row.pb_Audit === '1' || scope.row.pb_Audit === '2'"
              >
                编辑
              </el-button>
              <el-button 
                size="small" 
                type="warning" 
                @click="handAudit(scope.row)"
                :disabled="scope.row.pb_Audit === '1' || scope.row.pb_Audit === '2'"
              >
                审核
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleDelete(scope.row)"
                :disabled="scope.row.pb_Audit === '1' || scope.row.pb_Audit === '2'"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- Centered pagination -->
      <div class="pagination-center">
        <el-pagination
          small
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
  
  <!-- 审核对话框 -->
  <el-dialog v-model="centerDialogVisible" width="385" align-center header-align="left">
    <template #header>
      <div style="text-align: left; font-size: 16px; font-weight: bold;">
        审核
      </div>
    </template>
    <hr>
    <div style="text-align: left;padding: 10px 0px;">
      <p>审核结果</p>
      <div class="my-2 ml-4">
        <el-radio-group v-model="auditStatus">
          <el-radio value="1">通过</el-radio>
          <el-radio value="2">驳回</el-radio>
        </el-radio-group>
      </div>
      <div>
        <p>审核意见</p>
        <el-input v-model="auditOpinion" style="width: 350px;height: 90px;"
          :autosize="{ minRows: 4, maxRows: 4 }" type="textarea" placeholder="请输入" />
      </div>
    </div>
    <hr>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="updateAudit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router';
import { ref, onMounted, markRaw } from 'vue';
import { Delete } from '@element-plus/icons-vue'
import dayjs from 'dayjs';
import { useStore } from 'vuex';

export default {
  setup() {
    const store = useStore();
    const datamax = store.state.PO_UpdeteArray

    const centerDialogVisible = ref(false);
    const auditStatus = ref('1');
    const auditOpinion = ref('');
    const currentRow = ref(null);

    const Router = useRouter();
    const tableData = ref([]);
    const flattenedData = ref([]);
    const spanArr = ref([]);
    const Pb_code = ref('');
    const Vendor_name = ref('');
    const currentPage = ref(1);
    const pageSize = ref(10);
    const pageCount = ref(0);
    const loading = ref(false);
    const cwdata = ref([]);
    const userOptions = ref([]);
    const measureOptios = ref([]);
    const detailsData = ref([]);
    const PodetailsData = ref([]);

    const getStateText = (state) => {
      return state == 0 ? '未完成' : state == 2 ? '部分入库' : '全部入库';
    }

    const getAuditText = (status) => {
      return status === '1' ? '已审核' : status === '2' ? '驳回' : '未审核';
    }

    const calculateSubtotal = (row) => {
      return (row.po_number * (row.details_monovalent || 0)).toFixed(2);
    }

    const dairuku = (row) => {
      return (row.po_number - row.details_storage || 0).toFixed(2);
    }

    onMounted(() => {
      fill();
      count();
      CK();
      getUser();
      getMeasure();
    });

    function CK() {
      axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBySelect", {
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
      }).then((result) => {
        cwdata.value = result.data;
      }).catch((err) => {
        console.error(err);
      });
    }

    function getUser() {
      axios.get("http://localhost:5181/api/User/GetUsers", {
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
      }).then((result) => {
        userOptions.value = result.data;
      }).catch((err) => {
        console.error(err);
      });
    }

    function getMeasure() {
      axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
          dict_type: "db_measure"
        }, 
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        measureOptios.value = result.data;
      }).catch((err) => {
        console.info(err);
      });
    }

    function cwVaule(row) {
      if (!row) return "无";
      const warehouse = cwdata.value.find((w) => w.warehouse_code == row);
      return warehouse ? warehouse.warehouse_name : "无";
    }

    function userValue(row) {
      if (!row) return "无";
      const user = userOptions.value.find((u) => u.user_id == row);
      return user ? user.user_name : "无";
    }

    function measureValue(row) {
      if (!row) return "无";
      const parentDept = measureOptios.value.find((sex) => sex.dict_value == row);
      return parentDept ? parentDept.dict_label : "无";
    }

    const processData = (data) => {
      const flatData = [];
      spanArr.value = [];
      
      data.forEach(order => {
        const mainOrder = {
          ...order,
          pro_name: '',
          pro_code: '',
          pro_brand: '',
          pro_model: '',
          po_number: '',
          details_monovalent: '',
          details_storage: '',
        };
        
        const rowCount = order.details ? order.details.length : 1;
        spanArr.value.push(rowCount);
        
        if (order.details && order.details.length > 0) {
          order.details.forEach(detail => {
            flatData.push({ ...mainOrder, ...detail });
          });
        } else {
          flatData.push(mainOrder);
        }
      });
      
      return flatData;
    }

    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
    }

    const fill = () => {
      loading.value = true;
      axios.get("http://localhost:5181/api/Pb/GetPbFyWhere", {
        params: {
          Pb_code: Pb_code.value,
          Vendor_name: Vendor_name.value,
          currentPage: currentPage.value,
          pageSize: pageSize.value
        },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
      }).then((res) => {
        const formattedData = res.data.map(item => ({
          ...item,
          pb_Inboundtime: formatDate(item.pb_Inboundtime),
          create_time: formatDate(item.create_time),
          update_time: formatDate(item.update_time)
        }));
        
        tableData.value = formattedData;
        flattenedData.value = processData(formattedData);
      }).catch((err) => {
        console.error('数据加载失败', err);
        ElMessage.error('数据加载失败');
      }).finally(() => {
        loading.value = false;
      });
    }

    const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
      const mergeColumns = ['pb_code', 'pb_state', 'po_name', 'vendor_name', 'po_Starttime', 
                           'contacts_Name', 'contacts_Phone', 'po_Rep_Id', 'warehouse_Code', 
                           'pb_Audit', 'operation','warehouse_code','po_rep_id'];
      
      if (mergeColumns.includes(column.property)) {
        let position = 0;
        for (let i = 0; i < spanArr.value.length; i++) {
          const count = spanArr.value[i];
          if (rowIndex < position + count) {
            return {
              rowspan: rowIndex === position ? count : 0,
              colspan: 1
            };
          }
          position += count;
        }
      }
    }

    const count = () => {
      axios.get("http://localhost:5181/api/Pb/GetPbCount", {
        params: {
          Pb_code: Pb_code.value,
          Vendor_name: Vendor_name.value,
        },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
      }).then((res) => {
        pageCount.value = res.data;
      }).catch((err) => {
        console.error('总条数加载失败', err);
        ElMessage.error('总条数加载失败');
      });
    }

    const query = () => {
      currentPage.value = 1;
      fill();
      count();
    }

    function infoPage(row) {
      store.commit('PO_UpdeteArray', row)
      Router.push({
        path: '/main/Pinv/Pbinfo',
        // query: { rowData: JSON.stringify(row) }
      });
    }

    const reset = () => {
      Pb_code.value = '';
      Vendor_name.value = '';
      query();
    }

    const addEdit = () => {
      Router.push({ path: '/main/Pinv/PbAdd' });
    }

    const handleEdit = (row) => {
      if(row.pb_Audit > 0){
        ElMessage.error("已审核后的订单不可编辑");
      } else {
        store.commit('PO_UpdeteArray', row)
        Router.push({
          path: '/main/Pinv/PbUpdate',
          // query: { rowData: JSON.stringify(row) }
        });
      }
    }

    function handleDelete(row) {
      if(row.pb_Audit > 0){
        ElMessage.error("已审核后的订单不可删除");
      } else {
        ElMessageBox.confirm(
          '此操作将删除该产品信息，是否继续？',
          '警告',
          {
            type: 'warning',
            icon: markRaw(Delete),
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          }
        )
        .then(() => {
          return axios.put('http://localhost:5181/api/Pb/PutPbDelete', {
            pb_id: row.pb_id,
            del_flag: "1"
          }, {
            headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
          });
        })
        .then((result) => {
          if (result.data > 0) {
            ElMessage.success("删除成功");
            fill();
            count();
          } else {
            ElMessage.error("删除失败");
          }
        })
        .catch((error) => {
          console.error("删除失败:", error);
        });
      }
    }

    const handleSizeChange = (val) => {
      pageSize.value = val;
      fill();
    }
    
    const handleCurrentChange = (val) => {
      currentPage.value = val;
      fill();
    }
    
    // 审核按钮
    function handAudit(row) {
      if (row.pb_Audit == 0 || row.pb_Audit == null) {
        currentRow.value = row;
        centerDialogVisible.value = true;
      } else {
        ElMessage.warning('该入库单已被审核，不可再次审核！');
      }
    }
    
    // 关闭审核对话框
    function close() {
      centerDialogVisible.value = false;
      auditStatus.value = '1';
      auditOpinion.value = '';
    }
    
    // 审核确认按钮
    async function updateAudit() {
      try {
        // 获取明细数据
        const detailsResult = await axios.get("http://localhost:5181/api/Pb/Getpurwhsedetailwherecode", {
          params: { code: currentRow.value.pb_code },
          headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        detailsData.value = detailsResult.data;
        
        // 获取采购订单明细数据
        const poDetailsResult = await axios.get("http://localhost:5181/api/Po/Getdetailswherecode", {
          params: { code: currentRow.value.po_code },
          headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        PodetailsData.value = poDetailsResult.data;
        
        // 处理采购订单明细数据
        const details1 = PodetailsData.value.map(item => ({
          details_id: item?.details_id || 0,
          pro_Code: item.pro_code,
          Details_storage: (Number(item?.details_storage || 0) + Number(item?.to_be_stored_qty || 0)).toFixed(2)
        }));
        
        // 处理库存数据
        const details = detailsData.value.map(item => ({
          purwhsedetail_id: item.purwhsedetail_id,
          Details_storage: (Number(item.details_storage || 0) + Number(item.to_be_stored_qty || 0)).toFixed(2),
          To_be_stored_qty: item.to_be_stored_qty || 0,
          pb_id: item.pb_id || currentRow.value.pb_id,
          stock_name: item.pro_name || '',
          pro_code: item.pro_code || '',
          pro_brand: item.pro_brand || '',
          dict_code: item.unitmeas_id || '',
          pro_attribbute_id: '1',
          stock_model: item.pro_model || '',
          pro_sale_price: '',
          pro_cost_price: item.details_monovalent || 0,
          stock_numder: (Number(item.details_storage || 0) + Number(item.to_be_stored_qty || 0)).toFixed(2),
          stock_entry_no: currentRow.value.pb_code || '',
          warehouse_code: currentRow.value.warehouse_code || '',
          zone_code: currentRow.value.zone_code || '',
          location_code: item.location_code || '',
          vendor_code: currentRow.value.vendor_code || '',
          vendor_name: currentRow.value.vendor_name || '',
          create_by: localStorage.getItem('userLName') || '',
          create_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
          del_flag: "0"
        }));
        
        // 构建请求数据
        const requestData = {
          pinv_Po: {
            po_Id: currentRow.value.po_id || 0
          },
          pinv_Details: details1.map((item, index) => ({
            details_id: item.details_id,
            details_storage: details[index]?.To_be_stored_qty || item.Details_storage,
            pro_code: item.pro_Code
          })),
          pinv_Pb: {
            po_Id: currentRow.value.po_id || 0,
            pb_id: currentRow.value.pb_id || 0,
            pb_Audit_By: localStorage.getItem('userLName') || '',
            pb_Audit_Time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
            pb_Audit_Remark: auditOpinion.value || '',
            pb_Audit: auditStatus.value || '0'
          },
          pinv_Purwhsedetail: details.map(item => ({
            Purwhsedetail_id: item.purwhsedetail_id,
            details_storage: item.Details_storage,
            to_be_stored_qty: item.To_be_stored_qty,
            pb_id: item.pb_id,
            pb_code: currentRow.value.pb_code || '',
            pro_code: item.pro_code,
            Details_monovalent: item.pro_cost_price,
            warehouse_code: item.warehouse_code,
            zone_code: item.zone_code,
            location_code: item.location_code,
            vendor_code: item.vendor_code,
            vendor_name: item.vendor_name,
            create_by: item.create_by,
            create_time: item.create_time,
            del_flag: "0"
          }))
        };
        // console.log(requestData);
        
        // 发送审核请求
        const result = await axios.put("http://localhost:5181/api/Pb/PutPodetails_Pb_PbdetailsUpdate", requestData, {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        });
        
        if (!result.data) throw new Error('Empty response');
        
        switch (result.data.affectedRows) {
          case 1:
            ElMessage.success('审核成功！');
            fill(); // 刷新数据
            close();
            break;
          case 3:
            ElMessage.error('当前仓库、库区、库位中不存在此商品，请确认仓库、库区、库位！');
            break;
          case 2:
            ElMessage.error('产品不存在');
            break;
          case 10:
            ElMessage.error('事务回滚，未知错误，调试查看');
            break;
          case 4:
            ElMessage.error('未知错误');
            break;
          default:
            ElMessage.error(`未知返回码: ${result.data.affectedRows}`);
        }
      } catch (error) {
        console.error('审核失败:', error);
        ElMessage.error(`审核失败: ${error.message}`);
      }
    }

    return {
      tableData,
      flattenedData,
      Pb_code,
      Vendor_name,
      currentPage,
      pageSize,
      pageCount,
      loading,
      cwdata,
      userOptions,
      centerDialogVisible,
      auditStatus,
      auditOpinion,
      query,
      reset,
      addEdit,
      handleEdit,
      handleDelete,
      handleSizeChange,
      handleCurrentChange,
      objectSpanMethod,
      getStateText,
      getAuditText,
      calculateSubtotal,
      cwVaule,
      userValue,
      measureValue,
      dairuku,
      infoPage,
      handAudit,
      updateAudit,
      close
    }
  }
}
</script>

<style scoped>
.compact-container {
  padding: 10px;
  margin-top: -10px;
}

.search-row {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 6px;
  margin-top: -40px;
}

.search-label {
  white-space: nowrap;
  font-size: 13px;
}

.search-input {
  width: 160px !important;
}

.flex-grow {
  flex-grow: 1;
}

.table-wrapper {
  margin-top: 6px;
}

:deep(.el-table__row) {
  height: 36px !important;
}

:deep(.el-table th.el-table__cell) {
  height: 36px !important;
}

:deep(.el-button--small) {
  padding: 5px 8px;
  height: 24px;
}

.pagination-center {
  display: flex;
  justify-content: center;
  margin-top: 8px;
}

.action-group {
  display: flex;
  justify-content: center;
  gap: 4px;
}
</style>